package com.ruoyi.system.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.core.web.page.TableSupport;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.aop.TestAuth;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.listenetr.UserListener;
import com.ruoyi.system.service.IPostService;
import com.ruoyi.system.service.IRoleService;
import com.ruoyi.system.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@Api(tags = {"用户接口"})
@RestController
@RequestMapping("/users")
public class UserController extends BaseController
{
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPostService postService;
    @Autowired
    RedisTemplate redisTemplate;
    /**
     * 获取用户列表
     */
    @ApiOperation(value = "用户测试接口")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 600,message = "失败")
    })
    @RequiresPermissions("system:user:list")
    @GetMapping("/list")
    @TestAuth("用户测试字符")
    public TableDataInfo list(SysUser user)
    {
        Page<SysUser> page = new Page<>();
        page.setCurrent(Convert.toInt(ServletUtils.getParameter(TableSupport.PAGE_NUM), 1));
        page.setSize(Convert.toInt(ServletUtils.getParameter(TableSupport.PAGE_SIZE), 10));
        page = userService.selectPageVo(page,user);
        return getDataTable(page.getRecords(),page.getTotal());
    }

    /**
     * 新增用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysUser user)
    {
        if(!redisTemplate.opsForValue().setIfAbsent(JSONUtils.toJSONString(user),1,1, TimeUnit.MINUTES)){
            return warn("表单重读提交");
        }
        user.setCreateTime(new Date());
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return success(userService.saveAll(user));
    }

    /**
     * 根据用户编号获取详细信息
     */
    @RequiresPermissions("system:user:query")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.list();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.list());
        if (com.ruoyi.common.core.utils.StringUtils.isNotNull(userId))
        {
            SysUser sysUser = userService.getById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            List<Long> postIds = postService.selectPostListByUserId(userId);
            ajax.put("postIds",postIds);
            List<Long> roleIds = roleService.selectRoleListByUserId(userId);
            ajax.put("roleIds", roleIds);
        }
        return ajax;
    }

    /**
     * 修改用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        user.setUpdateTime(new Date());
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    @RequestMapping("down")
    public void selectList(HttpServletResponse response) throws IOException {
        List<SysUser> sysUsers = userService.list();

        String fileName = SysUser.class.getSimpleName();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(),SysUser.class).sheet("模板").doWrite(sysUsers);
    }

    @RequestMapping("upload")
    public Map<String, Object> upload(MultipartFile file) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        try {
            map.put("code",200);
            EasyExcel.read(file.getInputStream(),SysUser.class,new UserListener(userService)).sheet().doRead();
        }catch (IOException e){
            map.put("code",500);
            e.printStackTrace();
        }
        return map;
    }

}
